package com.xgp.weixinxgp.controller;

import com.sun.xml.internal.ws.util.xml.CDATA;
import com.xgp.weixinxgp.tool.WxTool;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;


@RestController
@RequestMapping("/wx")
public class WxController {

/*    参数	描述
    signature	微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
    timestamp	时间戳
    nonce	随机数
    echostr	随机字符串*/
    @GetMapping("/connect")
    public String connect(@RequestParam("signature") String signature,
                     @RequestParam("timestamp") String timestamp,
                     @RequestParam("nonce") String nonce,
                     @RequestParam("echostr") String echostr){

        if(WxTool.check(timestamp,nonce,signature)) {
            System.out.println("接入成功");
            return echostr;
        }
        return null;
    }

/*    文本消息
            <xml>
  <ToUserName><![CDATA[toUser]]></ToUserName>
  <FromUserName><![CDATA[fromUser]]></FromUserName>
  <CreateTime>1348831860</CreateTime>
  <MsgType><![CDATA[text]]></MsgType>
  <Content><![CDATA[this is a test]]></Content>
  <MsgId>1234567890123456</MsgId>
</xml>

    参数	描述
    ToUserName	开发者微信号
    FromUserName	发送方帐号（一个OpenID）
    CreateTime	消息创建时间 （整型）
    MsgType	消息类型，文本为text
    Content	文本消息内容
    MsgId	消息id，64位整型*/
    @PostMapping("/connect")
    public String connect(HttpServletRequest request, HttpServletResponse response) {
        //解决乱码问题
        try {
            request.setCharacterEncoding("utf8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setCharacterEncoding("utf8");
        //处理事件和推送
        Map<String,String> requestMap = null;
        try {
            requestMap = WxTool.parseRequest(request.getInputStream());
            System.out.println(requestMap);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //用于处理事件和消息的回复，放回的是xml数据包
        String respXml = WxTool.getResponse(requestMap);
/*        String respXml = "<xml>\n" +
                "  <ToUserName><![CDATA[" + requestMap.get("FromUserName") + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + requestMap.get("ToUserName")+ "]]></FromUserName>\n" +
                "  <CreateTime>" + System.currentTimeMillis()/1000 + "</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[hello world!]]></Content>\n" +
                "</xml>";*/
        System.out.println(respXml);
        return respXml;
    }
}
